<template>
  <div class="product-detail">
    <van-nav-bar title="商品详情" left-text="返回" left-arrow @click-left="$router.back()" />
    <div v-if="dataSource.info" class="product-container">
      <img :src="`${URL}/images/shangcheng/${dataSource.info.product_image}`" alt="Product Image"
        class="product-image" />
      <div class="product-info">
        <h2 class="product-title">{{ dataSource.info.product_name }}</h2>
        <p class="product-description">{{ dataSource.info.product_description }}</p>
        <p class="product-price">价格: <span>{{ dataSource.info.price * dataSource.num }}积分</span></p>
      </div >
      <van-stepper v-model="dataSource.num" min="0" integer :before-change="onChage" />
      <van-button type="primary" class="buy-button" @click="onBuy(dataSource.info.id)">购买</van-button>
    </div>
    <div v-else>
      <p>商品不存在或正在加载...</p>
    </div>
  </div>
</template>

<script setup>
import { ref, } from 'vue';
import { useRoute } from 'vue-router';
import { GET, POST } from "../../tools/fetch.js";
import { shopApi, baseURL } from "../../tools/api.js";
import { useUserStore } from "../../tools/storage.js";
import { showSuccessToast, showFailToast } from 'vant';

const route = useRoute();
const URL = baseURL;
const userStore = useUserStore();
const id = ref(route.query.id);
const dataSource = ref({
  info: {},
  num: 1,
});
const onLoad = async () => {
  const response = await GET({
    api: shopApi.info,
    data: { id: id.value }
  });
  dataSource.value.info = response.data;
};
onLoad();
const onChage = (value) => {
  const sum = value * dataSource.value.info.price;
  if (sum > userStore.userInfo.integral) {
    showFailToast("积分不足");
    return false;
  }
  return true;
};
const onBuy = async (id) => {
  const resResult = await POST({
    api: shopApi.buy,
    data: {
      id: id,
      count: dataSource.value.num,
    },
  });
  console.log(resResult); 
  userStore.setUserInfo(resResult.data);
  dataSource.value.num = 0;
  showSuccessToast('购买成功');
};
</script>

<style scoped lang="less">
.product-detail {
  padding: 20px;
}

.product-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.product-image {
  width: 100%;
  max-width: 400px;
  height: auto;
  border-radius: 10px;
}

.product-info {
  text-align: center;
  width: 100%;
  padding: 0 20px;
}

.product-title {
  margin: 10px 0;
  font-size: 24px;
  color: #333;
}

.product-description {
  margin: 10px 0;
  font-size: 16px;
  color: #666;
}

.product-price {
  font-size: 18px;
  color: #ff5c5c;
  margin: 10px 0;
}

.product-price span {
  font-weight: bold;
}

.buy-button {
  align-self: center;
  width: 90%;
  margin-top: 20px;
}
</style>